<template>
  <section class="main">
    <input
      id="toggle-all"
      class="toggle-all"
      type="checkbox"
      v-model="checkAll"
    />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <!-- These are here just to show the structure of the list items -->
      <!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
      <li
        :class="{ completed: item.done, editing: item.id === currentId }"
        v-for="item in list"
        :key="item.id"
      >
        <div class="view">
          <input
            class="toggle"
            type="checkbox"
            :checked="item.done"
            @change="changeFn(item.id)"
          />
          <label @dblclick="showEdit(item)">{{ item.name }}</label>
          <button class="destroy" @click="del(item.id)"></button>
        </div>
        <input
          class="edit"
          v-model="currentName"
          @keyup.enter="edit"
          @keyup.esc="cancel"
          v-main-focus
        />
      </li>
    </ul>
  </section>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      currentId: '',
      currentName: '',
    }
  },
  computed: {
    ...mapGetters('todos', {
      list: 'showList',
    }),
    checkAll: {
      get() {
        return this.list.every(item => item.done)
      },
      set(value) {
        this.$store.commit('todos/checkAll', value)
      },
    },
  },
  methods: {
    changeFn(id) {
      this.$store.commit('todos/changeDone', id)
    },
    del(id) {
      this.$store.commit('todos/del', id)
    },
    showEdit(item) {
      this.currentId = item.id
      this.currentName = item.name
    },
    cancel() {
      this.currentId = ''
      this.currentName = ''
    },
    edit() {
      this.$store.commit('todos/edit', {
        id: this.currentId,
        name: this.currentName,
      })

      this.currentId = ''
      this.currentName = ''
    },
  },
}
</script>

<style></style>
